# coding:utf-8
import shutil
from pathlib import Path
from typing import Any

from PyQt6.QtWidgets import QWidget, QVBoxLayout, QFileDialog
from qfluentwidgets import GroupHeaderCardWidget, FluentIcon as FIF, PushButton, ComboBox, PrimaryPushButton, InfoBar

from common import SingleIcon
from components import BaseScrollArea


class DeleteFileView(BaseScrollArea):
    title = '删除文件或文件夹'
    description = '跳过系统索引查询，直接从本地磁盘中删除文件或文件夹'
    is_shortcut = True
    object_name = 'DeleteFileView'
    icon = SingleIcon.DEL_FOLDER

    def __init__(self, parent: QWidget):
        super().__init__(parent)
        self.scrollLayout: QVBoxLayout
        self.fileName: str = ''
        self.headerCard = GroupHeaderCardWidget('删除文件或文件夹', self)
        self.typeComboBox = ComboBox(self)
        self.selectBtn = PushButton(FIF.FOLDER, '选择文件或文件夹', parent=self)
        self.deleteBtn = PrimaryPushButton(FIF.DELETE, '删除', parent=self)

        self.__initWidgets()
        self.__initGroup()
        self.__onConnectSignals()

    def __initWidgets(self):
        self.setObjectName('DeleteFileView')
        self.setReturnVisible(True)

        self.typeComboBox.addItem('文件')
        self.typeComboBox.addItem('文件夹')

        self.scrollLayout.addWidget(self.headerCard)

    def __initGroup(self):
        self.headerCard.addGroup(
            FIF.DATE_TIME,
            '类型',
            '选择要删除的类型',
            self.typeComboBox,
        )
        self.headerCard.addGroup(
            FIF.QUESTION,
            '名称',
            '输入要删除的文件或文件夹名称',
            self.selectBtn,
        )
        self.headerCard.addGroup(
            FIF.DELETE,
            '删除',
            '确认删除文件或文件夹',
            self.deleteBtn,
        )

    def __onConnectSignals(self):
        self.selectBtn.clicked.connect(self.onSelectBtnClicked)
        self.deleteBtn.clicked.connect(self.onDeleteBtnClicked)

    def onSelectBtnClicked(self):
        if self.typeComboBox.currentText() == '文件':
            filename, _ = QFileDialog.getOpenFileName(self, '选择文件', '', 'All Files (*)')
        else:
            filename = QFileDialog.getExistingDirectory(self, '选择文件夹', '')
        if filename:
            self.fileName = filename

    def onDeleteBtnClicked(self):
        if not self.fileName:
            return
        if self.typeComboBox.currentText() == '文件':
            self.load(lambda: Path(self.fileName).unlink())
        else:
            self.load(shutil.rmtree, self.fileName)

    def onFuncSuccess(self, result: Any):
        InfoBar.success('删除成功', f'{self.fileName} 已删除', duration=2000, parent=self.window())
        self.fileName = ''
